package com.siblings.loan.ui.steps.act

import android.net.Uri
import android.view.View
import androidx.camera.core.AspectRatio
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import com.lib.base.base.BaseActivity
import com.lib.base.utils.ImageUtil
import com.lib.base.utils.TitleBarUtil
import com.lib.base.utils.log.LogHelper
import com.siblings.http.callback.StringCallback
import com.siblings.http.model.Progress
import com.siblings.http.model.Response
import com.siblings.http.request.base.Request
import com.siblings.loan.app.Apps
import com.siblings.loan.databinding.ActCameraSelfieBinding
import com.siblings.loan.http.ApiService
import com.siblings.loan.http.HttpHelper
import com.siblings.loan.utils.dialog.KefuDialog
import com.siblings.loan.utils.event.SibEventType
import com.siblings.loan.utils.imagecovert.ImageConvert
import org.json.JSONObject
import java.io.File
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

/**
 * SiblingsLoan
 * @Author wwdeng
 * @CreateTime: 2024/7/12 17:12
 * @Annotation：自拍照
 */
class SibCameraSelfieAct: BaseActivity() {
    lateinit var binding: ActCameraSelfieBinding

    private lateinit var cameraExecutor: ExecutorService
    private var imageCapture: ImageCapture? = null
    private var imgUri: Uri? = null
    private var imgUsePath = ""

    override fun getSibRootView(): View {
        binding = ActCameraSelfieBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initSibView() {
        TitleBarUtil.setStatusBarLightMode(this, false)
        binding.titleLayout.setPadding(0, TitleBarUtil.getStatusBarHeight(),0,0)

        cameraExecutor = Executors.newSingleThreadExecutor()
        startCamera()
    }

    override fun initSibListener() {
        binding.imgBack.setOnClickListener {
            finish()
        }

        //客服
        binding.imgKefu.setOnClickListener {
            showSibKefuDialog("SelfieCamera Page")
            HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_CUSTOMER,"SelfieCamera Page")
        }

        //拍照
        binding.imgTakeCamera.setOnClickListener {
            HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_CAMERA_TAKE_PHOTO,"SelfieCamera Page")
            takeFilePhoto()
        }

        //重拍
        binding.remakeLayout.setOnClickListener {
            HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_STEP_SELFIE_REMAKE,"")
            showTakeView()
        }

        //使用
        binding.usePhotoLayout.setOnClickListener {
            HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_STEP_SELFIE_USE_PHOTO, imgUsePath)
            showSibLoading(isTOuchOut = false, isCancel = false)
            // 图片处理
            ImageConvert.covert(context = this, uri = imgUri) { localPath, bitmap ->
                if (localPath != null){
                    LogHelper.e("imageConvert success>>>>>>>$localPath")
                    onSibUploadImageAction(localPath)
                }
            }
        }
    }

    override fun initSibData() {
    }

    /**
     * 打开相机预览
     */
    private fun startCamera() {
        showTakeView()
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
        cameraProviderFuture.addListener(Runnable {
            val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
            val preview = Preview.Builder()
                .setTargetAspectRatio(AspectRatio.RATIO_16_9)
                .build()
                .also {
                    it.setSurfaceProvider(binding.carmeraView.surfaceProvider)
                }
            imageCapture = ImageCapture.Builder().build()
            //打开前置摄像头
            val cameraSelector = CameraSelector.DEFAULT_FRONT_CAMERA
            try {
                cameraProvider.unbindAll()
                cameraProvider.bindToLifecycle(this, cameraSelector, preview,imageCapture)
            } catch(exc: Exception) {
            }
        }, ContextCompat.getMainExecutor(this))
    }

    /**
     * 拍照并保存到本地
     */
    private fun takeFilePhoto(){
        if (imageCapture != null){
            //创建文件
            val filePath = Apps.app.filesDir.absolutePath
            val outputFile = File(filePath,"${System.currentTimeMillis()}.jpg")
            if (!outputFile.exists()){
                outputFile.mkdir()
            }
            //创建输出选项对象
            val metadata = ImageCapture.Metadata().apply {
                // 当为前置摄像头时镜像；前置摄像头预览时默认就是镜像
                isReversedHorizontal = true
            }
            //创建文件
            val outputFileOptions = ImageCapture.OutputFileOptions.Builder(outputFile).setMetadata(metadata).build()
            //开始拍照
            imageCapture!!.takePicture(outputFileOptions,ContextCompat.getMainExecutor(this),object : ImageCapture.OnImageSavedCallback{
                override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
                    imgUri = outputFileResults.savedUri
                    LogHelper.e("take photo complete>>>>>>>${imgUri!!.path}")
                    imgUsePath = imgUri!!.path!!
                    ImageUtil.instance!!.loadImageUrl(this@SibCameraSelfieAct,binding.imgPreview,imgUsePath,0)
                    showCompleteView()
                }
                override fun onError(exception: ImageCaptureException) {
                    LogHelper.e("take photo failed >>>>>>>${exception.message}")
                }
            })
        }
    }

    /**
     * 显示拍照样式
     */
    private fun showTakeView(){
        binding.imgPreview.visibility = View.GONE
        binding.imgTakeCamera.visibility = View.VISIBLE
        binding.remakeLayout.visibility = View.INVISIBLE
        binding.usePhotoLayout.visibility = View.INVISIBLE
    }

    /**
     * 显示拍照完成页面
     */
    private fun showCompleteView(){
        binding.imgPreview.visibility = View.VISIBLE
        binding.imgTakeCamera.visibility = View.INVISIBLE
        binding.remakeLayout.visibility = View.VISIBLE
        binding.usePhotoLayout.visibility = View.VISIBLE
    }

    /**
     * 上传图片
     */
    private fun onSibUploadImageAction(imgPath: String){
        val httpUrl = ApiService.getHttpUrl(ApiService.API_URL.SIB_API_UPLOAD_FILE_URL)
        HttpHelper.uploadSibFileAction(httpUrl,imgPath,object : StringCallback(){
            override fun onStart(request: Request<String, out Request<Any, Request<*, *>>>?) {
                super.onStart(request)
                LogHelper.e("upload start")
            }
            override fun onSuccess(response: Response<String>?) {
                LogHelper.e("upload success ："+response!!.body())
                if (response.code() == 200){
                    hideSibLoading()
                    val data = JSONObject(response!!.body())
                    when(data.optInt("code")){
                        0 -> {//成功
                            val imgUrl = data.optJSONObject("obj")!!.optString("url")
                            val intent = intent
                            intent.putExtra("imgLocalPath",imgUsePath)
                            intent.putExtra("imgUrl",imgUrl)
                            setResult(RESULT_OK,intent)
                            finish()
                        }
                        else -> {
                            val msg = data.optString("msg")
                            showSibToast(msg)
                        }
                    }
                } else {
                    showSibToast(response.message())
                }
            }
            override fun onError(response: Response<String>?) {
                LogHelper.e("upload error： "+response!!.body())
                showSibToast(response.message())
            }
            override fun uploadProgress(progress: Progress) {
                LogHelper.e("uploadProgress: $progress")
                LogHelper.e("uploadProgress，total: ${progress.totalSize}")
                LogHelper.e("uploadProgress，progress: ${progress.currentSize}")
            }
            override fun onFinish() {
                hideSibLoading()
            }
        })
    }

    /**
     * 显示客服dialog
     */
    private fun showSibKefuDialog(eventRemark: String){
        val kefuDialog = KefuDialog(this,eventRemark,object : KefuDialog.IDialogCallback{
            override fun onClick(view: View?) {
            }
        })
        kefuDialog.setCancelable(true)
        kefuDialog.setCanceledOnTouchOutside(true)
        kefuDialog.show()
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.addSibEventAction(SibEventType.PAGE.SIB_PAGE_STEP_SELFIE_CAMERA_START,"")
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addSibEventAction(SibEventType.PAGE.SIB_PAGE_STEP_SELFIE_CAMERA_END,"")
        cameraExecutor.shutdown()
    }
}